<template>
  <el-select
    v-model="modelValue"
    style="width: 100%"
    placeholder="点击选择用户"
    :multiple="multiple"
    :disabled="disabled"
    popper-class="dropdown"
    @visible-change="visible = true"
    @remove-tag="removeTag"
  >
    <el-option
      v-for="{ userId, cname } of selectedRows"
      :key="userId"
      :label="`${cname}`"
      :value="userId"
    />
  </el-select>
  <el-dialog
    v-if="visible"
    v-model="visible"
    title="用户选择"
    custom-class="modal"
    append-to-body
    width="90%"
    top="10vh"
  >
    <el-row>
      <el-col :span="4" style="max-height:600px;overflow:auto">
        <el-card shadow="never">
          <el-input v-model="filterOrg" placeholder="筛选部门" style="margin-bottom: 10px" />
          <el-tree
            ref="tree"
            :data="orgTree"
            node-key="id"
            :props="{ label: 'name', children: 'children' }"
            :filter-node-method="filterOrgTree"
            :default-expanded-keys="expandedKeys"
            :expand-on-click-node="false"
            @node-click="clickOrgTree"
          />
        </el-card>
      </el-col>
      <el-col :span="20">
        <search @on-search="onSearch" />
        <list
          v-model="selectedRows"
          :list-data="listData"
          :multiple="multiple"
          @change-page="changePage"
        />
      </el-col>
    </el-row>
    <template #footer>
      <el-button @click="onCancel">{{ $t('message.operate.cancel') }}</el-button>
      <el-button type="primary" @click="onOk">{{ $t('message.operate.confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getOrgTree ,fetchOrgTree} from '../../api/position'
import { fetchListRequest } from '../../api/deptMember'
import Search from './Search'
import List from './List'
import { get, filter, map } from 'lodash'

export default {
  components: {
    Search,
    List,
  },
  props: {
    modelValue: {
      type: [Array, String],
      required: true,
    },
    defaultUsers: {
      type: Array,
      required: true,
    },
    users: {
      type: Array,
      default() {
        return []
      },
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    orgid:{
      type:String,
      default: '',
    },
    disabled:{
      type: Boolean,
      default: false,
    }
  },
  emits: ['update:modelValue', 'update:users'],
  data() {
    return {
      visible: false,
      orgTree: [],
      expandedKeys:[],
      listData: {},
      selectedRows: {}, // 选中列表行
      params: {
        orgId: null,
        total: 0,
        size: 10,
        current: 1,
      },
      filterOrg: null,
    }
  },
  watch: {
    filterOrg(val) {
      this.$refs.tree?.filter(val)
    },
    visible() {
      if (this.visible) {
        this.getOrgs()
        this.fetchList()
      }
    },
    orgid:{
      handler(newName, oldName){
        if(this.defaultUsers.length!=0){
          this.selectedRows=this.defaultUsers
          console.log("fz",this.selectedRows);
          this.saveValue()
        }else{
          this.selectedRows={}
        }
      },
      immediate: true
      
      
    }
  },
  // mounted() {
  //   this.saveValue()
  // },
  methods: {
    async getOrgs() {
      try {
        const { data } = await getOrgTree()
        this.orgTree = get(data, 'data', [])
        this.expandedKeys = map(get(this.orgTree[0], 'children', []),({ id }) => id)
      } catch (err) {
        console.error(err)
      }
    },
    async fetchList() {
      try {
        const { data } = await fetchListRequest(this.params)
        this.listData = get(data, 'data', {})
      } catch (err) {
        console.error(err)
      }
    },
    filterOrgTree(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    clickOrgTree({ id }) {
      this.params.orgId = id
      this.fetchList()
    },
    saveValue() {
      if (this.multiple) {
        const userIds = map(this.selectedRows, ({ userId }) => userId)
        this.$emit('update:modelValue', userIds ?? null)
      } else {
        const userId = get(this.selectedRows, '[0].userId')
        this.$emit('update:modelValue', userId ?? null)
      }
      this.$emit('update:users', this.selectedRows)
    },
    onOk() {
      this.saveValue()
      this.visible = false
    },
    removeTag(tag) {
      this.selectedRows = filter(this.selectedRows, ({ userId }) => userId !== tag)
      this.saveValue()
    },
    onCancel() {
      this.saveValue()
      this.visible = false
    },
    onSearch(form) {
      this.params = {
        ...this.params,
        ...form,
        current: 1,
      }
      this.fetchList()
    },
    changePage(page) {
      this.params = {
        ...this.params,
        current: page,
      }
      this.fetchList()
    },
  },
}
</script>

<style lang="scss">
.modal {
  overflow: hidden;
}
.dropdown {
  display: none;
  .el-select-dropdown {
    display: none;
  }
}
</style>
